package com.lzh.db.template;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author zhehen.lu
 * @date 2025/8/15 11:05
 */
public class DynamicTransactionTemplate {
    @Autowired
    private TransactionTemplate transactionTemplate;

    public DynamicTransactionTemplate() {
    }

    public <T> T execute(TransactionCallback<T> action, String dsName) throws TransactionException {
        DynamicDataSourceContextHolder.push(dsName);

        Object object;
        try {
            object = this.transactionTemplate.execute(action);
        } finally {
            DynamicDataSourceContextHolder.poll();
        }

        return (T) object;
    }
}
